﻿using System.Linq;
using Daemon.Common;
using Daemon.Common.Helpers;
using Daemon.Infrustructure.EF;
using Daemon.Repository.EF.Enums;
using Daemon.Repository.Contract;
using Daemon.Model;
using System;
using System.Linq.Expressions;
using System.Collections.Generic;

namespace Daemon.Repository.EF
{
	public class TakeAwayUserOrderDetailRepository : Repository<TakeAwayUserOrderDetail>, ITakeAwayUserOrderDetailRepository
	{
		protected override Expression<Func<TakeAwayUserOrderDetail, int>> PrimaryKeyExpression => r => r.Id;

		public TakeAwayUserOrderDetailRepository(ApiDBContent context) : base(context)
		{
		}

		protected override IEnumerable<TakeAwayUserOrderDetail> IncludeRelationships(IEnumerable<TakeAwayUserOrderDetail> entities, ApiDBContent db)
		{
			GetGoodInfo(entities);

			return base.IncludeRelationships(entities, db);
		}

		private void GetGoodInfo(IEnumerable<TakeAwayUserOrderDetail> entities)
		{
			if (!RouteParameterHelper.CheckRouteParameter(RelationshipNames, TakeAwayUserOrderDetailRelationShipEnum.GoodInfo))
			{
				return;
			}

			var goodIds = entities.Select(r => r.GoodId).ToList();
			var dicGood = Context.TakeAwayGood.Where(r => goodIds.Contains(r.Id)).ToList().GroupBy(r => r.Id).ToDictionary(r => r.Key, r => r.FirstOrDefault());
			var ruleDetailIds = entities.Select(r => r.RuleDetailId.Split(',', StringSplitOptions.RemoveEmptyEntries).ToList()).ToList().SelectMany(r => r).Select(r => Convert.ToInt32(r)).ToList();
			var ruleDetailValues = Context.TakeAwayRuleDetailValue.Where(r => ruleDetailIds.Contains(r.Id)).ToList();
			foreach (var entity in entities)
			{
				if (dicGood.TryGetValue(entity.GoodId, out TakeAwayGood good))
				{
					entity.GoodName = good.Name;
					entity.GoodImg = good.CoverImg;
				}

				var currentRuleDetailIds = entity.RuleDetailId.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(r => Convert.ToInt32(r)).ToList();
				var currentProperties = ruleDetailValues.Where(r => currentRuleDetailIds.Contains(r.Id)).Select(r => r.Value).ToList();
				entity.Properties = currentProperties;
			}
		}
	}
}
